package com.task.core.service.impl;

import java.util.List;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.task.common.annotation.DataScope;
import com.task.common.domain.info.KeyAndValue;
import com.task.common.exception.ServiceException;
import com.task.common.utils.SecurityUtils;
import com.task.common.utils.uuid.UUID;
import com.task.core.domain.MissionGroupInfo;
import com.task.core.dto.request.MissionGroupRequestDTO;
import com.task.core.mapper.MissionGroupMapper;
import com.task.core.service.MissionGroupService;

/**
 * @author 迪迦.
 * @date 2024/10/30 15:40
 */
@Service("MissionGroupService")
public class MissionGroupServiceImpl implements MissionGroupService {

  @Resource
  private MissionGroupMapper missionGroupMapper;

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<MissionGroupInfo> getMissionGroupByPage(MissionGroupRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    return missionGroupMapper.getMissionGroupByPage(request);
  }

  @Override
  public MissionGroupInfo getMissionGroupByCodeOrName(String code, String name) {
    return missionGroupMapper.getMissionGroupByCodeOrName(code,  name);
  }

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<KeyAndValue> getMissionGroupForOption(MissionGroupRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    return missionGroupMapper.getMissionGroupForOption(request);
  }

  @Override
  public void addMissionGroup(MissionGroupRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    request.setCode(UUID.randomUUID().toString().replace("-", ""));
    missionGroupMapper.addMissionGroup(request);
  }

  @Override
  public void modifyMissionGroup(MissionGroupRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    Integer integer = missionGroupMapper.modifyMissionGroup(request);
    if(integer == 0) {
      throw new ServiceException("code不存在");
    }
  }

  @Override
  public void deleteMissionGroup(String missionGroupCode, Long userId) {
    if (missionGroupMapper.getUsedCount(missionGroupCode) > 0) {
      throw new ServiceException("有关联当前分组的任务,不允许删除");
    }
    Integer integer = missionGroupMapper.deleteMissionGroup(missionGroupCode, userId);
    if(integer == 0) {
      throw new ServiceException("code不存在");
    }
  }

  @Override
  public MissionGroupInfo getMissionGroupByCode(String missionGroupCode) {
    MissionGroupRequestDTO missionGroupRequestDTO = new MissionGroupRequestDTO();
    missionGroupRequestDTO.setCode(missionGroupCode);
    return missionGroupMapper.getMissionGroupByCode(missionGroupRequestDTO);
  }
}
